// 微信通知关怀系统页面逻辑
const app = getApp();

Page({
  data: {
    // 页面数据
    notificationEnabled: true,
    boundStatus: false,
    todayCount: 0,
    dailyLimit: 10,
    serviceQrcode: '/images/wechat-service-qr.png',
    
    // 通知设置
    settings: {
      enabled: true,
      capsuleCreated: true,
      capsuleOpened: true,
      moodRecorded: true,
      thiefActivated: true,
      periodReminder: true,
      dailySummary: false,
      weeklyReport: false,
      achievementUnlocked: true,
      specialMoment: true,
      emotionSync: true,
      quietStartTime: '22:00',
      quietEndTime: '08:00',
      frequencyLimit: 10
    },
    
    // 弹窗控制
    showBindPopup: false,
    showTimePicker: false,
    timePickerType: '',
    tempQuietTime: '',
    
    // 加载状态
    loading: false,
    saving: false
  },

  // 生命周期函数
  onLoad() {
    this.loadNotificationSettings();
    this.checkWechatBindStatus();
    this.getTodayNotificationCount();
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.boundStatus) {
      this.getTodayNotificationCount();
    }
  },

  // 加载通知设置
  async loadNotificationSettings() {
    try {
      this.setData({ loading: true });
      
      const res = await app.request({
        url: '/api/wechat/notification/settings',
        method: 'GET'
      });
      
      if (res.code === 200) {
        this.setData({
          settings: { ...this.data.settings, ...res.data },
          notificationEnabled: res.data.enabled
        });
      }
    } catch (error) {
      console.error('加载通知设置失败:', error);
      wx.showToast({
        title: '加载设置失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 检查微信绑定状态
  async checkWechatBindStatus() {
    try {
      const res = await app.request({
        url: '/api/user/wechat/status',
        method: 'GET'
      });
      
      if (res.code === 200) {
        this.setData({
          boundStatus: res.data.bound
        });
      }
    } catch (error) {
      console.error('检查绑定状态失败:', error);
    }
  },

  // 获取今日通知数量
  async getTodayNotificationCount() {
    try {
      const res = await app.request({
        url: '/api/wechat/notification/today-count',
        method: 'GET'
      });
      
      if (res.code === 200) {
        this.setData({
          todayCount: res.data.count,
          dailyLimit: res.data.limit
        });
      }
    } catch (error) {
      console.error('获取今日通知数量失败:', error);
    }
  },

  // 切换总开关
  async onToggleAllNotifications(e) {
    const enabled = e.detail;
    
    try {
      this.setData({ saving: true });
      
      const res = await app.request({
        url: '/api/wechat/notification/settings',
        method: 'PUT',
        data: {
          ...this.data.settings,
          enabled: enabled
        }
      });
      
      if (res.code === 200) {
        this.setData({
          notificationEnabled: enabled,
          'settings.enabled': enabled
        });
        
        wx.showToast({
          title: enabled ? '已开启通知' : '已关闭通知',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('更新通知设置失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ saving: false });
    }
  },

  // 设置变更
  async onSettingChange(e) {
    const { type } = e.currentTarget.dataset;
    const value = e.detail;
    
    try {
      this.setData({ saving: true });
      
      const newSettings = {
        ...this.data.settings,
        [type]: value
      };
      
      const res = await app.request({
        url: '/api/wechat/notification/settings',
        method: 'PUT',
        data: newSettings
      });
      
      if (res.code === 200) {
        this.setData({
          settings: newSettings
        });
        
        wx.showToast({
          title: '设置已更新',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('更新设置失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ saving: false });
    }
  },

  // 绑定微信服务号
  onBindWechat() {
    if (this.data.boundStatus) {
      return;
    }
    
    this.setData({ showBindPopup: true });
  },

  // 关闭绑定弹窗
  onCloseBindPopup() {
    this.setData({ showBindPopup: false });
  },

  // 确认绑定
  async onConfirmBind() {
    try {
      wx.showLoading({ title: '检查绑定状态...' });
      
      // 重新检查绑定状态
      await this.checkWechatBindStatus();
      
      if (this.data.boundStatus) {
        this.setData({ showBindPopup: false });
        wx.showToast({
          title: '绑定成功',
          icon: 'success'
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '请先关注"ForeverLove情感关怀"服务号，然后点击确认',
          showCancel: false
        });
      }
    } catch (error) {
      console.error('确认绑定失败:', error);
    } finally {
      wx.hideLoading();
    }
  },

  // 发送测试通知
  async onSendTestNotification() {
    if (!this.data.boundStatus) {
      wx.showModal({
        title: '提示',
        content: '请先绑定微信服务号',
        showCancel: false
      });
      return;
    }
    
    try {
      wx.showLoading({ title: '发送中...' });
      
      const res = await app.request({
        url: '/api/wechat/notification/test',
        method: 'POST',
        data: {
          templateType: 'capsule_created',
          testData: {
            partnerName: '亲爱的',
            capsuleTitle: '测试胶囊',
            openTime: '2024-12-25',
            description: '这是一条测试通知'
          }
        }
      });
      
      if (res.code === 200) {
        wx.showToast({
          title: '测试通知已发送',
          icon: 'success'
        });
      } else {
        wx.showModal({
          title: '发送失败',
          content: res.message || '请检查网络连接',
          showCancel: false
        });
      }
    } catch (error) {
      console.error('发送测试通知失败:', error);
      wx.showToast({
        title: '发送失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 查看通知历史
  onViewHistory() {
    wx.navigateTo({
      url: '/pages/notification/history'
    });
  },

  // 选择免打扰时间
  onSelectQuietTime(e) {
    const { type } = e.currentTarget.dataset;
    const currentTime = type === 'start' ? 
      this.data.settings.quietStartTime : 
      this.data.settings.quietEndTime;
    
    this.setData({
      showTimePicker: true,
      timePickerType: type,
      tempQuietTime: currentTime
    });
  },

  // 确认时间选择
  async onTimeConfirm(e) {
    const { timePickerType, tempQuietTime } = this.data;
    const newTime = e.detail;
    
    try {
      const newSettings = {
        ...this.data.settings,
        [timePickerType === 'start' ? 'quietStartTime' : 'quietEndTime']: newTime
      };
      
      const res = await app.request({
        url: '/api/wechat/notification/settings',
        method: 'PUT',
        data: newSettings
      });
      
      if (res.code === 200) {
        this.setData({
          settings: newSettings,
          showTimePicker: false
        });
        
        wx.showToast({
          title: '设置已更新',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('更新免打扰时间失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  // 取消时间选择
  onTimeCancel() {
    this.setData({ showTimePicker: false });
  },

  // 设置频率上限
  onSetFrequencyLimit() {
    const items = ['5条', '10条', '15条', '20条', '不限'];
    
    wx.showActionSheet({
      itemList: items,
      success: async (res) => {
        const limits = [5, 10, 15, 20, 999];
        const newLimit = limits[res.tapIndex];
        
        try {
          const newSettings = {
            ...this.data.settings,
            frequencyLimit: newLimit
          };
          
          const apiRes = await app.request({
            url: '/api/wechat/notification/settings',
            method: 'PUT',
            data: newSettings
          });
          
          if (apiRes.code === 200) {
            this.setData({
              settings: newSettings,
              dailyLimit: newLimit
            });
            
            wx.showToast({
              title: '设置已更新',
              icon: 'success'
            });
          }
        } catch (error) {
          console.error('更新频率上限失败:', error);
          wx.showToast({
            title: '更新失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 一键开启所有通知
  async onEnableAllNotifications() {
    try {
      wx.showLoading({ title: '开启中...' });
      
      const allEnabledSettings = {
        ...this.data.settings,
        enabled: true,
        capsuleCreated: true,
        capsuleOpened: true,
        moodRecorded: true,
        thiefActivated: true,
        periodReminder: true,
        achievementUnlocked: true,
        specialMoment: true,
        emotionSync: true
      };
      
      const res = await app.request({
        url: '/api/wechat/notification/settings',
        method: 'PUT',
        data: allEnabledSettings
      });
      
      if (res.code === 200) {
        this.setData({
          settings: allEnabledSettings,
          notificationEnabled: true
        });
        
        wx.showToast({
          title: '已全部开启',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('一键开启失败:', error);
      wx.showToast({
        title: '开启失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    try {
      await Promise.all([
        this.loadNotificationSettings(),
        this.checkWechatBindStatus(),
        this.getTodayNotificationCount()
      ]);
    } catch (error) {
      console.error('刷新失败:', error);
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: 'ForeverLove微信通知关怀',
      path: '/pages/notification/notification',
      imageUrl: '/images/notification-share.jpg'
    };
  }
});